package com.kg.fiber.service;

import org.json.JSONObject;

import com.kg.fiber.FiberviewApplication;
import com.kg.fiber.domain.NetNode;
import com.kg.fiber.domain.NetNodeState;

import lombok.Getter;
import lombok.extern.log4j.Log4j;

@Log4j
public class NodeModal {
	
	@Getter
	private NetNode node;
	
	private NetNodeState state = NetNodeState.Unknown;
	
	private long lastUpdate = 0L;

	public NodeModal(NetNode node) {
		super();
		this.node = node;
	}
	
	public boolean match(String host) {
		
		return node.getHost().equals(host);
		
	}
	
	public void dispatch(String from, JSONObject value) {
		
		if(!value.has("state")) {
			
			log.warn("Report has no state field.");
			
			return;
			
		}
		
		boolean warning = value.getBoolean("state");
		
		lastUpdate = System.currentTimeMillis();
		
		this.setState(warning ? NetNodeState.Warning : NetNodeState.Normal);
		
	}
	
	private void setState(NetNodeState newState) {
		
		if(state != newState) {
			
			state = newState;
			
			if(state == NetNodeState.Warning) {
				
				Warnings w = FiberviewApplication.getSpring().getBean(Warnings.class);
				w.feed(node);
				
			}
			
		}
		
	}
	
	public NetNodeState getState() {
		
		long now = System.currentTimeMillis();
		
		if(now - lastUpdate > 10000) {
			return NetNodeState.Unknown;
		} else {
			return state;
		}
		
	}

}
